package com.ktmall.ktmalluijava.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.ktmall.ktmalluijava.dto.LoginParams;
import com.ktmall.ktmalluijava.pojo.User;
import com.ktmall.ktmalluijava.service.UserService;
import com.ktmall.ktmalluijava.utils.ResMsg;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/5/23 下午3:47
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //存储生成的验证
    private static final Map<String,Long> codeCapt = new HashMap<>();

    @Resource
    private UserService userService;

    // 生成验证码（有效期5分钟）
    @GetMapping("/create")
    public void createCaptcha(HttpServletResponse response) throws Exception {
        // 生成随机4位数字验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        lineCaptcha.setGenerator(randomGenerator);
        lineCaptcha.createCode();
        //获取验证码并存入缓存
        String code = lineCaptcha.getCode();
        codeCapt.put(code,System.currentTimeMillis());
        //将图片写入响应
        response.setContentType("image/png");
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }

    @PostMapping("/login")
    public String login(@RequestBody LoginParams loginParams) {
        String userName = loginParams.getUserName();
        String password = loginParams.getPassword();
        String code = loginParams.getCode();
        // 验证码校验
        // 检查验证码是否存在
        if (!codeCapt.containsKey(code)) {
            return ResMsg.error("验证码错误或已过期", false);
        }
        // 检查有效期（5分钟）
        long createTime = codeCapt.get(code);
        if (System.currentTimeMillis() - createTime > 5 * 60 * 1000) {
            codeCapt.remove(code); // 清除过期验证码
            return ResMsg.error("验证码已过期", false);
        }
        codeCapt.remove(code); // 验证成功后清除
        User user = userService.getUserByNameAndPassword(userName, password);
        if(user==null){
            return ResMsg.error("用户名或密码错误");
        }
        return ResMsg.success("登录成功",user);
    }
}
